//
//  NetHandler.m
//  iMoney
//
//  Created by Sean McGrail on 2/10/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "NetHandler.h"
#import "iMoneyAppDelegate.h"

@implementation NetHandler

@synthesize delegate;

#define BUFFER_SIZE 1024

-(id) initWithNetService: (NSNetService*) netService: (id<NetHandlerDelegate>) netDelegate
{
	if(self = [super init])
	{
		if ([netService getInputStream:&inStream outputStream:&outStream]) {
			
			self.delegate = netDelegate;
			
			firstRead = YES;
			totalBytesRead= 0;
			numBytes=0;
		
			[self openStreams];
		}
		else
		{
			[delegate error:@"could not open streams"];
		}

	}
	
	return self;
}


- (void) openStreams
{
	
	inStream.delegate = self;
	[inStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
	[inStream open];
	
	
	outStream.delegate = self;
	[outStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
	[outStream open];
}


-(void) closeStreams
{
	
	[inStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
	[inStream release];
	
	[outStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
	[outStream release];
	
}



- (void) sendXML:(const NSString*) message
{
	const char* s = [message UTF8String];
	
	NSData *data = [[NSData alloc] initWithBytes:s length:[message length]];
	
	if (outStream){
		if([outStream write:[data bytes] maxLength:[data length]] == -1)
			[delegate progress: @"Failed sending data to peer"];
	}
	
	[data release];
	
}


- (void) stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
{
	switch(eventCode) {
		case NSStreamEventOpenCompleted:
		{
			
			
			break;
		}
		case NSStreamEventHasBytesAvailable:
		{
			if(stream == inStream)
			{
				
				//find out message size
				if(firstRead)
				{
					[delegate progress: @"Getting message size"];
					
					uint32_t buf[1];
					
					[inStream read:(uint8_t*)buf maxLength:sizeof(buf)];
					
					numBytes = CFSwapInt32BigToHost(buf[0]);
				
					firstRead = NO;
					mainData = [[NSMutableData alloc] initWithCapacity:numBytes];	
					
					//[delegate progress: [NSString stringWithFormat:@"Message size %d\n%d", numBytes,buf[0]]];
					
					return;
				}
				
				uint8_t buffer[BUFFER_SIZE]; 
				
				
				int bytesRead = [inStream read:buffer maxLength:sizeof(buffer)];
				if(bytesRead <= 0)
				{
					[delegate error: @"Failed receiveing data from peer"];
					break;
				}
				
				totalBytesRead+=bytesRead;
				[mainData appendBytes:buffer length:bytesRead];
				
				[delegate progress: [NSString stringWithFormat:@"%d bytes received"]];
				
				if(numBytes <=0)
				{
					[delegate error:@"Message Size not specified"];
					return;
				}
				
				
				if(totalBytesRead >= numBytes && numBytes >0)
				{
				
				
				NSString* xmlDataString = [[NSString alloc] initWithData:mainData encoding:NSASCIIStringEncoding];
			
				
				//NSLog(@"%@ %d", xmlDataString, [xmlDataString length]);
				
				//remove the first 2 bytes from the front (byte order marker)
				//NSData* xmlData = [[xmlDataString substringFromIndex:0] dataUsingEncoding:NSUTF8StringEncoding]; 
				
				NSData* xmlData = [xmlDataString dataUsingEncoding:NSASCIIStringEncoding]; 
				
				if(xmlData != nil)
				{
					if([[iMoneyAppDelegate getMoneyState] parseXmlFromData:xmlData])
					{
						[delegate done];
					}
					else
						[delegate error:@"Could not Parse XML Data"];
				}
				
				[xmlData release];
				[xmlDataString release];
				
				
				}
			}
			
			break;
		}
		case NSStreamEventErrorOccurred:
		{
			NSLog(@"%s", _cmd);
			[delegate error:  @"Error encountered on stream!"];			
			break;
		}
			
		case NSStreamEventEndEncountered:
		{
			
			[delegate error: @"Peer Disconnected"];
			
			break;
		}
	}
}


- (void)dealloc {

	[self closeStreams];
	
    [super dealloc];
}


@end
